import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "qrc:/qml/styles" as Styles

Control {
    id: control

    // 公共属性
    property alias model: listModel.model
    property alias currentIndex: listModel.currentIndex
    property alias currentText: listModel.currentText
    property alias currentValue: listModel.currentValue
    property string textRole: "text"
    property string valueRole: "value"
    property string displayText: currentIndex >= 0 ? currentText : placeholderText
    property string placeholderText: ""
    property bool editable: false

    // 信号
    signal activated(int index)

    // 尺寸
    implicitWidth: 120
    implicitHeight: 40

    // 下拉框背景
    background: Rectangle {
        color: control.enabled ? Styles.Theme.surface : Styles.Theme.surfaceVariant
        border.color: dropArea.containsMouse || popup.visible ? Styles.Theme.primary : Styles.Theme.border
        border.width: 1
        radius: Styles.Theme.radiusSmall

        // 悬停效果
        Rectangle {
            anchors.fill: parent
            radius: parent.radius
            color: Styles.Theme.primary
            opacity: dropArea.containsMouse && !popup.visible ? 0.05 : 0
            Behavior on opacity { NumberAnimation { duration: Styles.Theme.animationFast } }
        }
    }

    // 主要内容
    contentItem: Row {
        spacing: Styles.Theme.spacingSmall
        leftPadding: Styles.Theme.spacingNormal
        rightPadding: Styles.Theme.spacingNormal

        // 显示文本
        Text {
            id: displayLabel
            anchors.verticalCenter: parent.verticalCenter
            width: parent.width - dropIcon.width - parent.spacing - parent.leftPadding - parent.rightPadding
            text: control.displayText
            color: control.enabled ?
                   (currentIndex >= 0 ? Styles.Theme.textPrimary : Styles.Theme.textTertiary) :
                   Styles.Theme.textTertiary
            font.pixelSize: Styles.Theme.fontSizeNormal
            elide: Text.ElideRight
            verticalAlignment: Text.AlignVCenter
        }

        // 下拉箭头
        Text {
            id: dropIcon
            anchors.verticalCenter: parent.verticalCenter
            text: popup.visible ? "▲" : "▼"
            color: Styles.Theme.textSecondary
            font.pixelSize: 12
        }
    }

    // 鼠标区域
    MouseArea {
        id: dropArea
        anchors.fill: parent
        hoverEnabled: true
        cursorShape: Qt.PointingHandCursor
        enabled: control.enabled

        onClicked: {
            if (popup.visible) {
                popup.close()
            } else {
                popup.open()
            }
        }
    }

    // 数据模型管理
    QtObject {
        id: listModel
        property var model: []
        property int currentIndex: -1
        property string currentText: ""
        property var currentValue: null

        function updateCurrent() {
            if (currentIndex >= 0 && currentIndex < model.length) {
                var item = model[currentIndex]
                if (typeof item === "object") {
                    currentText = item[control.textRole] || ""
                    currentValue = item[control.valueRole] !== undefined ? item[control.valueRole] : item[control.textRole]
                } else {
                    currentText = item.toString()
                    currentValue = item
                }
            } else {
                currentText = ""
                currentValue = null
            }
        }

        onCurrentIndexChanged: {
            updateCurrent()
        }

        onModelChanged: updateCurrent()
    }

    // 监听父窗口状态，窗口关闭或不可见时自动关闭弹出框
    Connections {
        target: control.Window.window
        function onVisibleChanged() {
            if (target && !target.visible && popup.visible) {
                popup.close()
            }
        }
        function onActiveChanged() {
            if (target && !target.active && popup.visible) {
                popup.close()
            }
        }
    }

    // 监听Control自身的可见性
    onVisibleChanged: {
        if (!visible && popup.visible) {
            popup.close()
        }
    }

    // 下拉弹出框
    Popup {
        id: popup
        y: control.height
        width: control.width
        height: Math.min(listView.contentHeight + 2, 300)
        modal: false
        focus: false  // 不自动获取焦点，避免与父容器冲突
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideParent
        parent: Overlay.overlay  // 关键修复：使用Overlay作为父容器，确保显示在最上层

        // 手动计算全局位置
        x: {
            var globalPos = control.mapToItem(Overlay.overlay, 0, 0)
            return globalPos.x
        }

        Component.onCompleted: {
            // 确保y坐标也是相对于Overlay的
            var globalPos = control.mapToItem(Overlay.overlay, 0, control.height)
            popup.y = globalPos.y
        }

        onAboutToShow: {
            // 每次显示前更新位置，确保ComboBox移动后Popup仍在正确位置
            var globalPos = control.mapToItem(Overlay.overlay, 0, control.height)
            popup.x = globalPos.x
            popup.y = globalPos.y
        }

        // 监听Control被销毁，确保Popup也被关闭
        Component.onDestruction: {
            if (popup.visible) {
                popup.close()
            }
        }

        background: Rectangle {
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            // 阴影效果
            Rectangle {
                anchors.fill: parent
                anchors.topMargin: 2
                anchors.leftMargin: 2
                color: "black"
                opacity: 0.1
                radius: parent.radius
                z: -1
            }
        }

        contentItem: ListView {
            id: listView
            clip: true
            model: control.model
            currentIndex: listModel.currentIndex

            delegate: Item {
                width: listView.width
                height: 36

                property bool isHovered: mouseArea.containsMouse
                property bool isSelected: index === listModel.currentIndex

                Rectangle {
                    anchors.fill: parent
                    color: isSelected ? Styles.Theme.primary :
                           (isHovered ? Styles.Theme.surfaceVariant : "transparent")
                    opacity: isSelected ? 0.1 : (isHovered ? 0.5 : 0)
                }

                Text {
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.leftMargin: Styles.Theme.spacingNormal
                    anchors.rightMargin: Styles.Theme.spacingNormal

                    text: {
                        if (typeof modelData === "object") {
                            return modelData[control.textRole] || ""
                        } else {
                            return modelData.toString()
                        }
                    }
                    color: isSelected ? Styles.Theme.primary : Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    elide: Text.ElideRight
                    verticalAlignment: Text.AlignVCenter
                }

                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    hoverEnabled: true
                    cursorShape: Qt.PointingHandCursor

                    onClicked: {
                        listModel.currentIndex = index
                        control.activated(index)
                        popup.close()
                    }
                }
            }
        }

        onClosed: {
            control.forceActiveFocus()
        }
    }

    // 焦点处理
    Keys.onPressed: function(event) {
        if (event.key === Qt.Key_Space || event.key === Qt.Key_Return) {
            if (popup.visible) {
                popup.close()
            } else {
                popup.open()
            }
            event.accepted = true
        } else if (event.key === Qt.Key_Up) {
            if (listModel.currentIndex > 0) {
                listModel.currentIndex--
            }
            event.accepted = true
        } else if (event.key === Qt.Key_Down) {
            if (listModel.currentIndex < control.model.length - 1) {
                listModel.currentIndex++
            }
            event.accepted = true
        } else if (event.key === Qt.Key_Escape) {
            popup.close()
            event.accepted = true
        }
    }
}